//
//  RegisterSecondView.swift
//  ezyform
//
//  Created by MoennigQ on 8/9/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import RxGesture
class RegisterSecondView: GreenNaviBarView {
    lazy var disposeBag = DisposeBag()
    //
    let scrollView = DIYScrollView()
    let physicalAndPOBoxAddressView = PhysicalAndPOBoxAddressView()
    //底部操作按钮
    let backBtn = OperationButton(R.string.localizable.cancel(),backColor: UIColor(hexStr: "#70798A"))
    let submitBtn = OperationButton(R.string.localizable.submit())
    
    override func setUpView() {
        self.backgroundColor = .white
        //底部操作按钮
        self.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom).offset(Constant.BottomMargin)
            make.left.equalTo(16)
            make.height.equalTo(OperationButton.height)
            make.width.greaterThanOrEqualTo(0)
        }
        //submit
        self.addSubview(submitBtn)
        submitBtn.snp.makeConstraints { make in
            make.left.equalTo(backBtn.snp.right).offset(8)
            make.right.equalTo(-16)
            make.bottom.height.width.equalTo(backBtn)
        }
        //
        scrollView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        scrollView.backgroundColor = .white
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topBackView.snp.bottom).offset(-20)
            make.left.right.equalTo(self)
            make.bottom.equalTo(submitBtn.snp.top)
        }
        
        let contentView = UIView()
        contentView.backgroundColor = .clear
        scrollView.addSubview(contentView)
        
        contentView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        
        //address type title
        let addressTypeTitle = LabelWithRedStarView(R.string.localizable.addressType())
        contentView.addSubview(addressTypeTitle)
        addressTypeTitle.snp.makeConstraints { (make) in
            make.top.equalTo(20)
            make.left.equalTo(16)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //physicalAndPOBoxAddressView
        contentView.addSubview(physicalAndPOBoxAddressView)
        physicalAndPOBoxAddressView.snp.makeConstraints { (make) in
            make.top.equalTo(addressTypeTitle.snp.bottom).offset(12)
            make.left.equalTo(addressTypeTitle)
            make.right.equalTo(-16)
            make.height.greaterThanOrEqualTo(0)
        }
        //
        //login private policy
        
        //login private policy
        let privatePolicyLabel = HyperlinkLabel.banner(content: "By clicking submit, you agree to our", alignment: .left, customStyling: translatesAutoresizingMaskIntoConstraints) {(title ,url) in
//            if UIApplication.shared.canOpenURL(url){
//                UIApplication.shared.open(url, options: [:], completionHandler: nil)
//            }
            if let naviagtionVC =  self.firstNaviViewController(){
                let vc = AttachmentViewController()
                vc.attchmentType = .OtherLink
                vc.attachmentURL = url.absoluteString
                vc.attachmentTitle = title
                naviagtionVC.pushViewController(vc, animated: false)
            }
        }
        privatePolicyLabel.addBanner(linkContentStr: R.string.localizable.privacyPolicy(), linkStr: APPConfig.serverAddress + APIConfig.LoginprivacyPolicy, customStyling: true)
        privatePolicyLabel.addStr(content: " and ")
        privatePolicyLabel.addBanner(linkContentStr: R.string.localizable.termsAndConditions(), linkStr: APPConfig.serverAddress + APIConfig.LoginTermsConditions, customStyling: true)

//        let privatePolicyLabel = HyperlinkLabel.banner(content: "By clicking submit, you agree to our %0$@", linkContentStr: R.string.localizable.privacyPolicy(),linkStr: APPConfig.serverAddress + APIConfig.RegisterprivacyPolicy,withAlignment: .left, customStyling: true, tapHandler: { url in
//            if UIApplication.shared.canOpenURL(url){
//                UIApplication.shared.open(url, options: [:], completionHandler: nil)
//            }
//        })
        privatePolicyLabel.numberOfLines  = 0
        privatePolicyLabel.adjustsFontSizeToFitWidth = true
        contentView.addSubview(privatePolicyLabel)
        privatePolicyLabel.snp.makeConstraints { (make) in
            make.top.equalTo(physicalAndPOBoxAddressView.snp.bottom).offset(20)
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-20)
            
        }
    }
    func setData(_ model: PhysicalAndPOBoxAddressViewModel){
        self.physicalAndPOBoxAddressView.setData(model)
        self.checkEverythingValid()
    }
    //MARK: - 必填项数据绑定控制continue btn是否可用
    private func checkEverythingValid(){
        //1.2绑定
        let poBoxTypeValid = self.physicalAndPOBoxAddressView.poBoxTypeLabel.rx.observe(Int.self, "tag").map({$0 == 1}).share(replay: 1)
        let poNumberValid = self.physicalAndPOBoxAddressView.poBoxNumberTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        let postCodeValid = self.physicalAndPOBoxAddressView.postcodeTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        //
        let poBoxValid = Observable.combineLatest(
            poBoxTypeValid,
            poNumberValid,
            postCodeValid
        ) { //$0 && $1 && $2
            if $0 && $1 && $2 {
                return true
            }else{
                return false
            }
        }
        .share(replay: 1)
        //2.physical address
        //2.1这里提取验证是为了处理，返回又进入做处理
        //1.po box
        
        //2.2绑定
        let physicalTypeValid = self.physicalAndPOBoxAddressView.physicalTypeLabel.rx.observe(Int.self, "tag").map({$0 == 1}).share(replay: 1)
        let unitNoValid = self.physicalAndPOBoxAddressView.editPhysicalAddress.unitNoTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        let streetNoValid = self.physicalAndPOBoxAddressView.editPhysicalAddress.streetNoTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        let streetNameValid = self.physicalAndPOBoxAddressView.editPhysicalAddress.streetNameTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        let streetTypeValid = self.physicalAndPOBoxAddressView.editPhysicalAddress.streetTypeTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        let physicalPostCode = self.physicalAndPOBoxAddressView.editPhysicalAddress.postcodeTextfield.validStatus.map({$0 == .valid}).share(replay: 1)
        
        let physicalAddressValid = Observable.combineLatest(
            unitNoValid,
            physicalTypeValid,
            streetNoValid,
            streetNameValid,
            streetTypeValid,
            physicalPostCode
        ) { //$0 && $1 && $2 && $3 && $4 && $5
            if $0 && $1 && $2 && $3 && $4 && $5 {
                return true
            }else{
                return false
            }
        }
        .share(replay: 1)
        //3.everything valid, po box或者physical address必填项满足
        let everythingValid = Observable.combineLatest(
            poBoxValid,
            physicalAddressValid
        ) { $0 || $1}
        .share(replay: 1)
        
        everythingValid.subscribe { [weak self] (valid) in
            guard let strongSelf = self else {return}
            if valid {
                strongSelf.submitBtn.enableBtn()
            }else{
                strongSelf.submitBtn.disableBtn()
            }
        }.disposed(by: self.disposeBag)
    }
}
